<script setup>
import { ref, computed, onMounted } from 'vue';
import { Icon } from '@iconify/vue';
import { useI18n } from 'vue-i18n';
import { listPlugins, uninstallRuntimePlugin, installPluginFromDirectory } from '../../services/pluginManager';
import { invoke } from '@tauri-apps/api/core';
import { open as openDialog } from '@tauri-apps/plugin-dialog';
import { getAppSetting } from '../../tauriApi';

const { t } = useI18n();

// Plugin data
const installedPlugins = ref([]);
const isLoading = ref(true);

const isTauri = typeof window !== 'undefined' && !!window.__TAURI_INTERNALS__;

const categories = computed(() => {
  const cats = {};
  installedPlugins.value.forEach(plugin => {
    const cat = plugin.category || 'general';
    if (!cats[cat]) cats[cat] = [];
    cats[cat].push(plugin);
  });
  return cats;
});

const categoryOrder = ['language', 'general', 'themes', 'debuggers', 'formatters', 'other'];

function getCategoryIcon(category) {
  const icons = {
    language: 'codicon:symbol-class',
    general: 'codicon:extensions',
    themes: 'codicon:color-mode', 
    debuggers: 'codicon:debug',
    formatters: 'codicon:symbol-method',
    other: 'codicon:package'
  };
  return icons[category] || 'codicon:package';
}

function getCategoryName(category) {
  const names = {
    language: 'Language Support',
    general: 'General',
    themes: 'Themes',
    debuggers: 'Debuggers', 
    formatters: 'Formatters',
    other: 'Other'
  };
  return names[category] || category;
}

function getActivationEventText(events) {
  if (!events || events.length === 0) return 'Manual';
  return events.map(event => {
    if (event === 'onStartup') return 'Startup';
    if (event === 'onCommand') return 'On Command';
    if (event.startsWith('onLanguage:')) return `Language: ${event.split(':')[1]}`;
    return event;
  }).join(', ');
}

async function refreshList(){
  isLoading.value = true;
  try {
    const list = await listPlugins();
    installedPlugins.value = Array.isArray(list) ? list : [];
  } catch (e) {
    console.error('Failed to list plugins', e);
    installedPlugins.value = [];
  } finally {
    isLoading.value = false;
  }
}

async function togglePlugin(plugin) {
  // For now, only support deactivation of runtime plugins via uninstall; built-ins are managed by activation events
  if (plugin.source === 'built-in') {
    alert('Built-in plugins cannot be disabled from here yet.');
    return;
  }
  if (plugin.isActive) {
    // soft-deactivate by calling uninstallRuntimePlugin (keeps directory in settings if needed)
    const ok = await uninstallRuntimePlugin(plugin.name);
    if (ok) await refreshList();
  } else {
    // Reinstall/load from remembered dir if available
    if (plugin.dir) {
      await installPluginFromDirectory(plugin.dir);
      await refreshList();
    } else {
      alert('Missing plugin directory to enable. Please reinstall from folder.');
    }
  }
}

async function uninstallPlugin(plugin) {
  if (plugin.source === 'built-in') {
    alert('Built-in plugins cannot be uninstalled.');
    return;
  }
  if (confirm(`Are you sure you want to uninstall "${plugin.displayName}"?`)) {
    const ok = await uninstallRuntimePlugin(plugin.name);
    if (ok) await refreshList();
  }
}

async function openPluginFolder() {
  if (!isTauri) { alert('Opening folder is only available in desktop mode.'); return; }
  try {
    const root = await getAppSetting('pluginsRoot');
    if (root) await invoke('open_in_new_window', { path: root });
    else alert('No extensions folder configured. Use Install from folder to add plugins.');
  } catch (e) {
    console.error(e);
  }
}

async function installFromFolder() {
  if (!isTauri) { alert('Install from folder is only available in desktop mode.'); return; }
  try {
    const sel = await openDialog({ directory: true, multiple: false, title: 'Select plugin folder' });
    if (!sel) return;
    const dir = Array.isArray(sel) ? sel[0] : sel;
    await installPluginFromDirectory(String(dir));
    await refreshList();
  } catch (e) {
    console.error('Install from folder failed', e);
  }
}

onMounted(async () => {
  await refreshList();
});
</script>

<template>
  <div class="flex flex-col h-full">
    <!-- Header with actions -->
    <div class="flex items-center justify-between px-2 py-2 border-b dark:border-neutral-700">
      <div class="flex items-center gap-2">
        <Icon icon="codicon:extensions" width="16" height="16" class="text-blue-600 dark:text-blue-400" />
        <span class="text-sm font-medium text-slate-700 dark:text-neutral-200">
          {{ t ? (t('extensions.installed') || 'Installed') : 'Installed' }}
        </span>
        <span class="text-xs text-slate-500 dark:text-neutral-400" v-if="!isLoading">
          ({{ installedPlugins.length }})
        </span>
      </div>
      
      <div class="flex items-center gap-1">
        <button
          class="h-6 w-6 flex items-center justify-center rounded hover:bg-slate-100 dark:hover:bg-neutral-700"
          @click="openPluginFolder"
          title="Open Extensions Folder"
        >
          <Icon icon="codicon:folder-opened" width="12" height="12" />
        </button>
        <button
          class="h-6 w-6 flex items-center justify-center rounded hover:bg-slate-100 dark:hover:bg-neutral-700"
          @click="installFromFolder"
          title="Install from Folder"
        >
          <Icon icon="codicon:add" width="12" height="12" />
        </button>
      </div>
    </div>

    <!-- Loading state -->
    <div v-if="isLoading" class="flex-1 flex items-center justify-center">
      <div class="flex items-center gap-2 text-sm text-slate-500 dark:text-neutral-400">
        <Icon icon="codicon:sync" width="16" height="16" class="animate-spin" />
        Loading extensions...
      </div>
    </div>

    <!-- Extensions list -->
    <div v-else class="flex-1 overflow-auto">
      <div v-if="installedPlugins.length === 0" class="flex flex-col items-center justify-center h-full text-center p-4">
        <Icon icon="codicon:extensions" width="48" height="48" class="text-slate-300 dark:text-neutral-600 mb-3" />
        <div class="text-sm text-slate-500 dark:text-neutral-400 mb-2">No extensions installed</div>
        <button
          class="text-xs text-blue-600 dark:text-blue-400 hover:underline"
          @click="installFromFolder"
        >
          Install from folder
        </button>
      </div>

      <div v-else>
        <!-- Group by category -->
        <template v-for="catKey in categoryOrder" :key="catKey">
          <div v-if="categories[catKey]">
            <div class="px-2 py-1 bg-slate-50 dark:bg-neutral-800/30 border-b dark:border-neutral-700">
              <div class="flex items-center gap-2 text-xs font-medium text-slate-600 dark:text-neutral-300">
                <Icon :icon="getCategoryIcon(catKey)" width="12" height="12" />
                {{ getCategoryName(catKey) }}
                <span class="text-slate-400 dark:text-neutral-500">({{ categories[catKey].length }})</span>
              </div>
            </div>

            <div v-for="plugin in categories[catKey]" :key="plugin.id" 
                 class="px-2 py-3 border-b border-slate-100 dark:border-neutral-800 hover:bg-slate-50 dark:hover:bg-neutral-800/50">
              <div class="flex items-start justify-between">
                <div class="flex-1 min-w-0">
                  <!-- Plugin header -->
                  <div class="flex items-center gap-2 mb-1">
                    <div class="flex items-center gap-2">
                      <div class="text-sm font-medium text-slate-800 dark:text-neutral-100 truncate">
                        {{ plugin.displayName }}
                      </div>
                      <span class="text-xs text-slate-500 dark:text-neutral-400">
                        v{{ plugin.version }}
                      </span>
                    </div>
                    <div class="flex items-center gap-1">
                      <div 
                        class="w-2 h-2 rounded-full"
                        :class="plugin.isActive ? 'bg-green-500' : 'bg-slate-300 dark:bg-neutral-600'"
                        :title="plugin.isActive ? 'Active' : 'Inactive'"
                      ></div>
                    </div>
                  </div>

                  <!-- Plugin description -->
                  <div class="text-xs text-slate-600 dark:text-neutral-400 mb-2 line-clamp-2">
                    {{ plugin.description }}
                  </div>

                  <!-- Plugin details -->
                  <div class="flex items-center gap-3 text-xs text-slate-500 dark:text-neutral-500">
                    <span>{{ plugin.author }}</span>
                    <span>•</span>
                    <span>{{ getActivationEventText(plugin.activationEvents) }}</span>
                    <template v-if="plugin.source==='runtime' && plugin.dir">
                      <span>•</span>
                      <span class="truncate" :title="plugin.dir">{{ plugin.dir }}</span>
                    </template>
                  </div>
                </div>

                <!-- Plugin actions -->
                <div class="flex items-center gap-1 ml-2">
                  <button
                    class="h-6 w-6 flex items-center justify-center rounded hover:bg-slate-200 dark:hover:bg-neutral-700"
                    @click="togglePlugin(plugin)"
                    :title="plugin.isActive ? 'Disable' : 'Enable'"
                  >
                    <Icon 
                      :icon="plugin.isActive ? 'codicon:debug-pause' : 'codicon:play'" 
                      width="12" 
                      height="12" 
                      :class="plugin.isActive ? 'text-orange-600' : 'text-green-600'"
                    />
                  </button>
                  <button
                    class="h-6 w-6 flex items-center justify-center rounded hover:bg-slate-200 dark:hover:bg-neutral-700 text-red-600"
                    @click="uninstallPlugin(plugin)"
                    title="Uninstall"
                  >
                    <Icon icon="codicon:trash" width="12" height="12" />
                  </button>
                </div>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- Footer info -->
    <div class="px-2 py-2 border-t dark:border-neutral-700 bg-slate-50 dark:bg-neutral-800/30">
      <div class="text-xs text-slate-500 dark:text-neutral-400 text-center">
        {{ t ? (t('extensions.footer') || 'Plugin System Active') : 'Plugin System Active' }}
      </div>
    </div>
  </div>
</template>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;  
  overflow: hidden;
}
</style>